package com.ljkj.blockpay.ui.fragment;

import static android.content.ContentValues.TAG;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.kongzue.baseokhttp.util.JsonMap;
import com.ljkj.blockpay.R;
import com.ljkj.blockpay.basedata.BaseFragment;
import com.ljkj.blockpay.basedata.BuildConfig;
import com.ljkj.blockpay.databinding.FragmentAssetBinding;
import com.ljkj.blockpay.databinding.FragmentMineBinding;
import com.ljkj.blockpay.presenter.AssetPresenter;
import com.ljkj.blockpay.presenter.MinePresenter;
import com.ljkj.blockpay.presenter.inter.MinePresenterInter;
import com.ljkj.blockpay.util.CameraUtils;
import com.ljkj.blockpay.util.ToggleToActivity;
import com.ljkj.blockpay.widget.ClickListener;
import com.ljkj.blockpay.widget.CommonDialog;
import com.luck.picture.lib.tools.ToastUtils;

public class MineFragment  extends BaseFragment<FragmentMineBinding, MinePresenter> implements MinePresenterInter.MinePresenterInterView,ClickListener {

    private CommonDialog mPhotoDialog;
    String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath();
    public static final String[] permissionsGroup =new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private Uri uri;
    ActivityResultLauncher<Intent> activityResultLauncher;
    public static MineFragment newInstance() {
        MineFragment fragment = new MineFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {

        });


    }

    @Override
    protected int initContentView() {
        return R.layout.fragment_mine;
    }


    @Override
    protected void initView() {
        super.initView();
        binding.setOnClick(this::onClick);
    }

    @Override
    protected void initData() {
        super.initData();
        if (!BuildConfig.getToken().isEmpty()){
            getPresenter().userInfo();
            binding.btnLoginout.setVisibility(View.VISIBLE);
        } else {
            binding.btnLoginout.setVisibility(View.GONE);
        }
    }

    @Override
    protected MinePresenter createPresenter() {
        return new MinePresenter(getActivity(),this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.rl_mine:
//                ToggleToActivity.toMyProfileActivity(getActivity());
                mPhotoDialog = CommonDialog.Builder.with(getActivity())
                        .setContentView(R.layout.uploadway_layout)
                        .forGravity(Gravity.BOTTOM)
                        .setCancelable(true).setOnClickListener(R.id.tv_uploadalbum, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (CameraUtils.checkSelectPhotoPermission(getActivity()) && CameraUtils.checkCropPermission(getActivity())) {//检查权限
                                    //有权限，打开相册
                                    openAlbum();
                                } else {
                                    //无权限，申请
                                    CameraUtils.requestSelectPhotoPermissions(getActivity());
                                }
                            }
                        }).setOnClickListener(R.id.tv_uploadphoto, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (CameraUtils.checkTakePhotoPermission(getActivity()) && CameraUtils.checkCropPermission(getActivity())) {//检查权限
                                    //有权限，打开相机
                                    openCamera();
                                } else {
                                    //无权限，申请
                                    CameraUtils.requestTakePhotoPermissions(getActivity());
                                }
                            }
                        })
                        .setOnClickListener(R.id.btn_cancel, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {

                            }
                        }).fullWidth().create();
                mPhotoDialog.show();
                    break;
            case R.id.rl_real:
                ToggleToActivity.toRealNameAuthenticationActivity(getActivity());
                break;
            case R.id.rl_safe:
                ToggleToActivity.toAccountsSecurityActivity(getActivity());
                break;
            case R.id.rl_preferences:
                ToggleToActivity.toPreferencesActivity(getActivity());
                break;
            case R.id.rl_amentionddress:
                ToggleToActivity.toMMAddressActivity(getActivity());
                break;
            case R.id.rl_rewardinviting:
                ToggleToActivity.toInvitingActivity(getActivity());
                break;
            case R.id.rl_aboutus:
                ToggleToActivity.toAboutUsActivity(getActivity());
                break;
            case R.id.btn_loginout:
                getPresenter().logout();
                BuildConfig.cleanToken();
                binding.btnLoginout.setVisibility(View.GONE);
                ToggleToActivity.toMainActivity(getActivity());
                break;

            default:
                break;
        }
    }
    //打开相机
    private void openCamera() {
        uri = null;
        uri = CameraUtils.openCamera(getActivity(), "test", "albumDir");
        mPhotoDialog.dismiss();
    }

    //打开相册
    private void openAlbum() {
        uri = null;
        CameraUtils.openAlbum(getActivity());
        mPhotoDialog.dismiss();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        //权限申请回调
        if (requestCode == CameraUtils.CAMERA_TAKE_PHOTO_PERMISSION) {
            //相机权限申请回调
            if (CameraUtils.checkTakePhotoPermission(getActivity()) && requestCode == CameraUtils.CAMERA_CROP_PERMISSION) {
                openCamera();
            } else {
                //权限不足
                Log.e(TAG, "相机权限不足");
            }
        } else if (requestCode == CameraUtils.CAMERA_SELECT_PHOTO_PERMISSION && requestCode == CameraUtils.CAMERA_CROP_PERMISSION) {
            //相册权限申请回调
            if (CameraUtils.checkSelectPhotoPermission(getActivity())) {
                openAlbum();
            } else {
                //权限不足
                Log.e(TAG, "相册权限不足");
            }
        }

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == CameraUtils.CAMERA_TAKE_PHOTO) {
            //相机跳转回调
//            binding.ivImage.setImageURI(uri);//展示图片
            Glide.with(mActivity).load(uri).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(binding.ivImage);
            //通知系统相册更新信息
            CameraUtils.updateSystem(getActivity(), uri);
        } else if (requestCode == CameraUtils.CAMERA_SELECT_PHOTO) {
            //相册跳转回调
            if (data != null){
//                binding.ivImage.setImageURI(data.getData());
                Glide.with(mActivity).load(data.getData()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(binding.ivImage);
                uri = data.getData();
            }
        }


    }


    @Override
    public void logoutSuccess(JsonMap jsonMap) {

    }

    @Override
    public void searchInfoSuccess(JsonMap jsonMap) {

        if (jsonMap.getInt("authLevel") == 0){
            binding.tvApprove.setText("未认证");
        } else if (jsonMap.getInt("authLevel") == 1){
            binding.tvApprove.setText("已认证");
        }

    }
}